from PyQt5.QtWidgets import (
    QWidget, QVBoxLayout, QHBoxLayout, QPushButton,
    QTableWidget, QTableWidgetItem, QHeaderView,
    QLineEdit, QComboBox, QGroupBox, QFormLayout,
    QMessageBox, QAbstractItemView, QDialog, QTextEdit
)
from PyQt5.QtGui import QColor, QFont
from PyQt5.QtCore import Qt
import datetime
from bank_manage_system.admin.customer_manager import CustomerManager


class CustomerFormDialog(QDialog):
    """客户信息表单对话框 - 严格匹配表结构"""

    def __init__(self, db, customer_data=None, parent=None):
        super().__init__(parent)
        self.db = db
        self.customer_data = customer_data or {}
        self.setWindowTitle("客户信息" if customer_data else "新增客户")
        self.setFixedSize(400, 300)
        self.initUI()

    def initUI(self):
        layout = QFormLayout()

        # 客户姓名 (customerName)
        self.name_edit = QLineEdit()
        self.name_edit.setPlaceholderText("请输入客户姓名")
        layout.addRow("姓名:", self.name_edit)

        # 证件号码 (PID)
        self.id_number_edit = QLineEdit()
        self.id_number_edit.setPlaceholderText("请输入18位身份证号")
        layout.addRow("证件号码(PID):", self.id_number_edit)

        # 电话号码 (telephone)
        self.phone_edit = QLineEdit()
        self.phone_edit.setPlaceholderText("请输入联系电话")
        layout.addRow("电话号码:", self.phone_edit)

        # 联系地址 (address)
        self.address_edit = QTextEdit()
        self.address_edit.setPlaceholderText("请输入详细地址")
        self.address_edit.setFixedHeight(60)
        layout.addRow("联系地址:", self.address_edit)

        # 按钮区域
        btn_layout = QHBoxLayout()
        submit_btn = QPushButton("保存")
        submit_btn.setStyleSheet("background-color: #4cd137; color: white; padding: 5px;")
        submit_btn.clicked.connect(self.accept)

        cancel_btn = QPushButton("取消")
        cancel_btn.setStyleSheet("background-color: #e84118; color: white; padding: 5px;")
        cancel_btn.clicked.connect(self.reject)

        btn_layout.addWidget(submit_btn)
        btn_layout.addWidget(cancel_btn)
        layout.addRow(btn_layout)

        # 填充现有数据（编辑模式）
        if self.customer_data:
            self.fill_form_data()

        self.setLayout(layout)

    def fill_form_data(self):
        """填充表单数据 - 严格匹配表字段"""
        self.name_edit.setText(self.customer_data.get('customerName', ''))
        self.id_number_edit.setText(self.customer_data.get('PID', ''))
        self.phone_edit.setText(self.customer_data.get('telephone', ''))
        self.address_edit.setText(self.customer_data.get('address', ''))

    def get_form_data(self):
        """获取表单数据 """
        return {
            'customerName': self.name_edit.text().strip(),
            'PID': self.id_number_edit.text().strip(),
            'telephone': self.phone_edit.text().strip(),
            'address': self.address_edit.toPlainText().strip()
        }


class CustomerTab(QWidget):
    def __init__(self, db):
        super().__init__()
        self.db = db
        self.manager = CustomerManager(db)  # 客户管理器实例
        self.initUI()

    def initUI(self):
        main_layout = QVBoxLayout()

        # 搜索功能区
        search_group = QGroupBox("客户搜索")
        search_layout = QFormLayout()

        self.search_type = QComboBox()
        # 根据表字段提供搜索选项
        self.search_type.addItems(["按客户ID", "按姓名", "按证件号码", "按电话号码", "按地址"])
        search_layout.addRow("查询方式:", self.search_type)

        self.search_input = QLineEdit()
        self.search_input.setPlaceholderText("输入查询条件...")
        search_layout.addRow("查询条件:", self.search_input)

        search_btn = QPushButton("搜索")
        search_btn.setStyleSheet("background-color: #487eb0; color: white; padding: 5px;")
        search_btn.clicked.connect(self.search_customers)

        reset_btn = QPushButton("重置")
        reset_btn.setStyleSheet("background-color: #7f8c8d; color: white; padding: 5px;")
        reset_btn.clicked.connect(self.reset_search)

        btn_layout = QHBoxLayout()
        btn_layout.addWidget(search_btn)
        btn_layout.addWidget(reset_btn)

        search_layout.addRow(btn_layout)
        search_group.setLayout(search_layout)
        main_layout.addWidget(search_group)

        # 客户表格
        self.table = QTableWidget()
        self.table.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.table.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.table.setSelectionMode(QAbstractItemView.SingleSelection)
        self.table.setSortingEnabled(True)
        self.table.setColumnCount(7)

        headers = [
            "客户ID", "姓名", "证件号码(PID)",
            "电话号码", "地址", "开户时间", "最后编辑时间"
        ]

        self.table.setHorizontalHeaderLabels(headers)
        self.table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.table.horizontalHeader().setFont(QFont("Arial", 10, QFont.Bold))
        self.table.verticalHeader().setVisible(False)

        main_layout.addWidget(self.table)

        # 操作按钮
        btn_layout = QHBoxLayout()

        self.add_btn = QPushButton("新增客户")
        self.add_btn.setStyleSheet("background-color: #4cd137; color: white; padding: 5px;")
        self.add_btn.clicked.connect(self.add_customer)

        self.edit_btn = QPushButton("修改信息")
        self.edit_btn.setStyleSheet("background-color: #0097e6; color: white; padding: 5px;")
        self.edit_btn.clicked.connect(self.edit_customer)

        self.delete_btn = QPushButton("删除客户")
        self.delete_btn.setStyleSheet("background-color: #e84118; color: white; padding: 5px;")
        self.delete_btn.clicked.connect(self.delete_customer)

        refresh_btn = QPushButton("刷新列表")
        refresh_btn.setStyleSheet("background-color: #8c7ae6; color: white; padding: 5px;")
        refresh_btn.clicked.connect(self.load_customers)

        btn_layout.addWidget(self.add_btn)
        btn_layout.addWidget(self.edit_btn)
        btn_layout.addWidget(self.delete_btn)
        btn_layout.addWidget(refresh_btn)

        main_layout.addLayout(btn_layout)
        self.setLayout(main_layout)

        # 初始加载客户数据
        self.load_customers()

    def load_customers(self):
        """从userinfo表加载客户数据"""
        try:
            query = "SELECT userinfo.customerID, customerName, PID, telephone, address,openDate FROM userinfo,cardinfo Where cardinfo.customerID = userinfo.customerID ORDER BY customerID DESC LIMIT 100"
            results = self.db.execute_query(query)

            self.table.setRowCount(len(results))

            for row_idx, row in enumerate(results):
                self.table.setItem(row_idx, 0, self.create_table_item(row.get('customerID', '')))
                self.table.setItem(row_idx, 1, self.create_table_item(row.get('customerName', '')))
                self.table.setItem(row_idx, 2, self.create_table_item(row.get('PID', '')))
                self.table.setItem(row_idx, 3, self.create_table_item(row.get('telephone', '')))
                self.table.setItem(row_idx, 4, self.create_table_item(row.get('address', '')))

                # 开户时间处理
                open_account_time = row.get('openDate')
                if not open_account_time:
                    open_account_time = datetime.datetime(2025, 6, 21)
                self.table.setItem(row_idx, 5, self.format_date(open_account_time))

                # 最后编辑时间
                self.table.setItem(row_idx, 6, self.format_date(row.get('updatedAt', '')))

            # 高亮新添加的行
            if hasattr(self, 'last_added_id'):
                self.highlight_row_by_id(self.last_added_id)

            # 状态更新
            if len(results) > 0:
                self.table.selectRow(0)
            else:
                self.table.setRowCount(1)
                self.table.setItem(0, 0, QTableWidgetItem("没有找到客户数据"))

        except Exception as e:
            QMessageBox.critical(self, "加载失败", f"加载客户数据时出错: {str(e)}")

    def create_table_item(self, value):
        """创建表格项并设置居中"""
        item = QTableWidgetItem(str(value))
        item.setTextAlignment(Qt.AlignCenter)
        return item

    def format_date(self, date_value):
        """格式化日期显示"""
        try:
            if isinstance(date_value, datetime.datetime):
                return QTableWidgetItem(date_value.strftime("%Y-%m-%d %H:%M:%S"))
            elif date_value:
                # 尝试解析字符串格式的日期
                if isinstance(date_value, str):
                    try:
                        date_value = datetime.datetime.strptime(date_value, "%Y-%m-%d %H:%M:%S")
                    except:
                        # 尝试其他常见格式
                        try:
                            date_value = datetime.datetime.fromisoformat(date_value)
                        except:
                            # 最终回退到字符串截取
                            date_value = date_value[:19]
                return QTableWidgetItem(str(date_value)[:19])
            return QTableWidgetItem("2025-06-21")  # 默认值
        except:
            return QTableWidgetItem("2025-06-21")  # 默认值

    def highlight_row_by_id(self, customer_id):
        """通过客户ID高亮行"""
        for row in range(self.table.rowCount()):
            if self.table.item(row, 0).text() == str(customer_id):
                for col in range(self.table.columnCount()):
                    self.table.item(row, col).setBackground(QColor(179, 229, 252))
                self.table.selectRow(row)
                self.table.scrollToItem(self.table.item(row, 0))
                break

    def search_customers(self):
        """根据条件搜索客户 - 使用CustomerManager"""
        search_text = self.search_input.text().strip()
        search_type_index = self.search_type.currentIndex()

        if not search_text:
            QMessageBox.warning(self, "搜索", "请输入搜索条件")
            return

        try:
            # 映射搜索类型
            search_mapping = {
                0: "exact",  # 按客户ID
                1: "fuzzy",  # 按姓名
                2: "exact",  # 按证件号码
                3: "fuzzy",  # 按电话号码
                4: "fuzzy"  # 按地址
            }

            # 获取搜索类型
            search_type = search_mapping.get(search_type_index, "fuzzy")

            # 使用CustomerManager执行搜索
            result = self.manager.search_customers(search_type, search_text)

            if not result['success']:
                QMessageBox.warning(self, "搜索失败", result['message'])
                return

            results = result['data']
            self.table.setRowCount(len(results))

            # 填充搜索结果
            for row_idx, row in enumerate(results):
                self.table.setItem(row_idx, 0, self.create_table_item(row.get('customerID', '')))
                self.table.setItem(row_idx, 1, self.create_table_item(row.get('customerName', '')))
                self.table.setItem(row_idx, 2, self.create_table_item(row.get('PID', '')))
                self.table.setItem(row_idx, 3, self.create_table_item(row.get('telephone', '')))
                self.table.setItem(row_idx, 4, self.create_table_item(row.get('address', '')))

                # 开户时间处理
                open_account_time = row.get('openDate')
                if not open_account_time:
                    open_account_time = datetime.datetime(2025, 6, 21)
                self.table.setItem(row_idx, 5, self.format_date(open_account_time))

                # 最后编辑时间（从数据库获取）
                self.table.setItem(row_idx, 6, self.format_date(row.get('updatedAt', '')))

            # 显示搜索结果
            if results:
                QMessageBox.information(self, "搜索结果", f"找到 {len(results)} 条记录")
            else:
                QMessageBox.information(self, "搜索结果", "没有找到匹配的客户")

        except Exception as e:
            QMessageBox.critical(self, "搜索失败", f"搜索客户数据时出错: {str(e)}")

    def reset_search(self):
        """重置搜索条件"""
        self.search_input.clear()
        self.load_customers()

    def add_customer(self):
        """添加新客户 - 使用CustomerManager"""
        dialog = CustomerFormDialog(self.db)
        if dialog.exec_() == QDialog.Accepted:
            form_data = dialog.get_form_data()

            # 验证必填字段
            if not form_data['customerName']:
                QMessageBox.warning(self, "添加失败", "客户姓名不能为空")
                return

            if not form_data['PID']:
                QMessageBox.warning(self, "添加失败", "证件号码不能为空")
                return
            elif len(form_data['PID']) != 18 or not form_data['PID'].isdigit():
                QMessageBox.warning(self, "添加失败", "证件号码必须是18位数字")
                return

            # 添加开户时间（当前时间）
            form_data['openDate'] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

            # 使用CustomerManager添加客户
            result = self.manager.add_customer(form_data)

            if result['success']:
                # 获取新添加的客户ID
                new_customer = self.db.execute_query(
                    "SELECT customerID FROM userinfo WHERE PID = %s",
                    (form_data['PID'],)
                )

                if new_customer:
                    self.last_added_id = new_customer[0]['customerID']
                    QMessageBox.information(self, "添加成功", result['message'])
                    self.load_customers()
            else:
                QMessageBox.critical(self, "添加失败", result['message'])

    def edit_customer(self):
        """编辑选中的客户 - 使用CustomerManager"""
        selected_row = self.table.currentRow()
        if selected_row < 0:
            QMessageBox.warning(self, "编辑客户", "请先选择一个客户")
            return

        customer_id = self.table.item(selected_row, 0).text()

        try:
            # 获取客户原始数据
            customer = self.db.execute_query(
                "SELECT * FROM userinfo WHERE customerID = %s",
                (customer_id,)
            )

            if not customer:
                QMessageBox.warning(self, "编辑失败", "未找到该客户信息")
                return

            # 创建编辑对话框
            dialog = CustomerFormDialog(self.db, customer[0], self)
            if dialog.exec_() == QDialog.Accepted:
                update_data = dialog.get_form_data()

                # 验证必填字段
                if not update_data['customerName']:
                    QMessageBox.warning(self, "编辑失败", "客户姓名不能为空")
                    return

                if not update_data['PID']:
                    QMessageBox.warning(self, "编辑失败", "证件号码不能为空")
                    return
                elif len(update_data['PID']) != 18 or not update_data['PID'].isdigit():
                    QMessageBox.warning(self, "编辑失败", "证件号码必须是18位数字")
                    return

                # 添加最后编辑时间
                update_data['updatedAt'] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

                # 使用CustomerManager更新客户
                result = self.manager.update_customer(int(customer_id), update_data)

                if result['success']:
                    QMessageBox.information(self, "编辑成功", result['message'])
                    self.load_customers()
                else:
                    QMessageBox.critical(self, "编辑失败", result['message'])

        except Exception as e:
            QMessageBox.critical(self, "编辑失败", f"更新客户信息时出错: {str(e)}")

    def delete_customer(self):
        """删除选中的客户 - 使用CustomerManager"""
        selected_row = self.table.currentRow()
        if selected_row < 0:
            QMessageBox.warning(self, "删除客户", "请先选择一个客户")
            return

        customer_id = self.table.item(selected_row, 0).text()
        customer_name = self.table.item(selected_row, 1).text()

        reply = QMessageBox.question(
            self, "确认删除",
            f"确定要删除客户吗？\n客户ID: {customer_id}\n客户姓名: {customer_name}",
            QMessageBox.Yes | QMessageBox.No, QMessageBox.No
        )

        if reply == QMessageBox.Yes:
            try:
                # 使用CustomerManager删除客户
                result = self.manager.delete_customer(int(customer_id))

                if result['success']:
                    QMessageBox.information(self, "删除成功", result['message'])
                    self.load_customers()
                else:
                    QMessageBox.warning(self, "删除失败", result['message'])
            except Exception as e:
                QMessageBox.critical(self, "删除失败", f"删除客户时出错: {str(e)}")